<template>
  <div>
    <div class="filter-container">
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="用户名/手机号/姓名" v-model="listQuery.filterUPN">
      </el-input>
      <el-button class="filter-item" rigth style="margin-rigth: 10px;" @click="handleCreate" type="primary" icon="el-icon-plus">{{$t('userInfo.table.add')}}</el-button>
    </div>
    <el-table border highlight-current-row height="350" :data="list" style="width: 100%;" @cell-click='rowClick' show-summary>

      <el-table-column label="姓名" fixed="left" show-overflow-tooltip>
        <template slot-scope="scope">
          {{scope.row.name}}
        </template>
      </el-table-column>
      <el-table-column label="登录名" min-width="120" align="center">
        <template slot-scope="scope">
          {{scope.row.username}}
        </template>
      </el-table-column>
      <el-table-column label="电话" min-width="120" align="center">
        <template slot-scope="scope">
          {{scope.row.phoneNumber}}
        </template>
      </el-table-column>
      <el-table-column label="性别" min-width="120" align="center">
        <template slot-scope="scope">
          {{scope.row.sex | sexFilter}}
        </template>
      </el-table-column>
      <el-table-column label="年龄" min-width="120" align="center">
        <template slot-scope="scope">
          {{scope.row.age}}
        </template>
      </el-table-column>
      <el-table-column label="折扣" min-width="120" align="center">
        <template slot-scope="scope">
          {{scope.row.discount | discountFilter}}
        </template>
      </el-table-column>
      <el-table-column label="预存款" min-width="120" align="center" prop="preDeposit">
        <template slot-scope="scope">
          {{scope.row.preDeposit}}
        </template>
      </el-table-column>
      <el-table-column label="总消费" min-width="120" align="center" prop="totalConsumption">
        <template slot-scope="scope">
          {{scope.row.totalConsumption | currency}}
        </template>
      </el-table-column>
      <el-table-column label="积分" min-width="120" align="center" prop="integral">
        <template slot-scope="scope">
          {{scope.row.integral | currency}}
        </template>
      </el-table-column>
      <el-table-column label="职业" min-width="120" align="center">
        <template slot-scope="scope">
          {{scope.row.occupation}}
        </template>
      </el-table-column>
      <el-table-column label="地址" min-width="120" align="center">
        <template slot-scope="scope">
          {{scope.row.address}}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" min-width="180" align="center">
        <template slot-scope="scope">
          {{scope.row.createdAt | moment('YYYY-MM-DD hh:mm:ss')}}
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <!-- <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page" :page-sizes="[10,20,30,50]" :page-size="listQuery.limit" layout="total, sizes, prev, pager, next, jumper" :total="total"> -->
      <el-pagination background small @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.page" :page-size="listQuery.limit" layout="prev, pager, next" :total="total">
      </el-pagination>
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :before-close="handleClose">
      <el-popover ref="addRecordsPopover" placement="right" width="400" trigger="click">
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item :label="$t('userInfo.table.records')">
            <el-input v-model="addReocrd"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleAddReocrd">添加</el-button>
          </el-form-item>
        </el-form>
      </el-popover>
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="right" label-width="70px" style='width: 400px; margin-left:50px;'>
        <el-form-item :label="$t('userInfo.table.discount')" prop="discount">
          <el-input-number :min="0.01" :max="1" :step="0.01" v-model="temp.discount"></el-input-number>
        </el-form-item>
        <el-form-item :label="$t('userInfo.table.records')" prop="records">
          <el-select class="filter-item" multiple default-first-option v-model="temp.records" placeholder="请选择">
            <el-option v-for="item in records" :key="item.id" :label="item.display" :value="item.id">
            </el-option>
          </el-select>

          <el-tooltip content="添加病史" placement="top">
            <el-button type="primary" icon="el-icon-plus" v-popover:addRecordsPopover></el-button>
          </el-tooltip>
        </el-form-item>
        <el-form-item :label="$t('userInfo.table.username')" prop="username">
          <el-input v-model="temp.username" placeholder="请输入登录名">
          </el-input>
        </el-form-item>
        <el-form-item :label="$t('userInfo.table.phoneNumber')" prop="phoneNumber">
          <el-input v-model="temp.phoneNumber" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item :label="$t('userInfo.table.name')" prop="name">
          <el-input v-model="temp.name" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item :label="$t('userInfo.table.sex')" prop="sex">
          <el-switch v-model="temp.sex" active-color="#13ce66" inactive-color="#ff4949" active-value=1 inactive-value=2 active-text="女" inactive-text="男">
          </el-switch>
        </el-form-item>
        <el-form-item :label="$t('userInfo.table.dateOfBirth')">
          <!-- <div class="demonstration">值：{{ temp.dateOfBirth }}</div> -->
          <el-date-picker v-model="temp.dateOfBirth" type="date" placeholder="选择日期" format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item :label="$t('userInfo.table.address')">
          <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="请输入地址" v-model="temp.address">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{$t('table.cancel')}}</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">{{$t('table.confirm')}}</el-button>
        <el-button v-else type="primary" @click="updateData">{{$t('table.confirm')}}</el-button>
      </div>
    </el-dialog>

    <!-- <el-dialog :title="预存款管理" :visible.sync="preDialogFormVisible" :before-close="handleClose">
    </el-dialog> -->
  </div>
</template>

<script>
import { getUserList, createUser, updateUser } from '@/api/user'
import { getRecordList, addRecord } from '@/api/record'

export default {
  data() {
    return {
      addReocrd: '',
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        filterUPN: ''
      },
      records: [],
      temp: {
        id: undefined,
        discount: 1,
        username: '',
        phoneNumber: '',
        dateOfBirth: '',
        address: '',
        name: '',
        sex: 1,
        records: []
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        username: [{ required: true, message: '登录名必须输入', trigger: 'change' }],
        phoneNumber: [{ required: true, message: '手机号必须输入', trigger: 'change' }],
        name: [{ required: true, message: '姓名必须输入', trigger: 'change' }],
        discount: [{ required: true, message: '折扣必须输入', trigger: 'change' }]
      },
      preDialogFormVisible: false
    }
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        success: 'success',
        pending: 'danger'
      }
      return statusMap[status]
    },
    currency(num, fString = '￥', cNum = 2) {
      return fString + Number(num).toFixed(cNum)
    },
    sexFilter(sex) {
      const sexMap = {
        1: '女',
        2: '男',
        0: '保密'
      }
      return sexMap[sex]
    },
    discountFilter(discount) {
      return discount * 10 + ' 折'
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      getUserList(this.listQuery.page, this.listQuery.limit, this.listQuery.filterUPN).then(response => {
        var data = response.data
        this.list = data.results
        this.total = data.count
        this.list.forEach(element => {
          if (!element.records) {
            element.records = []
          } else {
            const records = []
            element.records.forEach(record => {
              records.push(record.id)
            })
            element.records = records
          }
        })
        // console.log(this.list)
      })
      getRecordList().then(response => {
        var data = response.data
        this.records = data
      })
    },
    handleFilter() {
      this.fetchData()
    },
    rowClick(row, column, cell, event) {
      // console.log(row)
      // console.log(event)
      // console.log(column)
      // console.log(column.label)
      if (column.label !== '操作') {
        this.handleUpdate(row)
      } else {
        this.handleCreatePre(row)
      }
    },
    handleCreatePre(row) {
      this.preDialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.fetchData()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        discount: 1,
        username: '',
        phoneNumber: '',
        dateOfBirth: '',
        address: '',
        name: '',
        sex: 1,
        records: []
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => { })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createUser(this.temp).then((response) => {
            const data = response.data
            if (data.flag) this.list.unshift(this.temp)
            this.dialogFormVisible = !data.flag
            this.$notify({
              title: '创建用户',
              message: data.flag ? '创建成功' : data.errorMsg,
              type: data.flag ? 'success' : 'error',
              duration: 5000
            })
            this.fetchData()
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateUser(tempData.id, tempData).then((response) => {
            for (const v of this.list) {
              if (v.id === this.temp.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.temp)
                break
              }
            }
            const data = response.data
            this.dialogFormVisible = !data.flag
            this.$notify({
              title: '更新用户',
              message: data.flag ? '更新成功' : data.errorMsg,
              type: data.flag ? 'success' : 'error',
              duration: 5000
            })
            this.fetchData()
          })
        }
      })
    },
    handleAddReocrd() {
      const tempData = { 'display': this.addReocrd }
      addRecord(tempData).then(response => {
        const data = response.data
        this.$notify({
          title: '添加成功',
          message: data.flag ? '添加病史成功' : data.errorMsg,
          type: data.flag ? 'success' : 'error',
          duration: 5000
        })
        if (data.flag) this.addReocrd = ''
        getRecordList().then(response => {
          var data = response.data
          this.records = data
        })
      })
    }
  }
}
</script>
